/*
 * @lc app=leetcode.cn id=21 lang=typescript
 *
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function mergeTwoLists(
    list1: ListNode | null,
    list2: ListNode | null
): ListNode | null {
    if (!list1 || !list2) return list1 || list2;
    let head = new ListNode();
    let now = head;
    while (list1 && list2) {
        let val: number;
        if (list1.val < list2.val) {
            val = list1.val;
            list1 = list1.next;
        } else {
            val = list2.val;
            list2 = list2.next;
        }
        now.next = new ListNode(val);
        now = now.next;
    }
    now.next = list1 || list2;
    return head.next;
}
// @lc code=end
